package com.wudl.govern.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：wudl
 * @date ：Created in 2022-04-05 21:11
 * @description：String字符串处理类
 * @modified By：
 * @version: 1.0
 */

public class StringHelper {
    private static Logger logger = LoggerFactory.getLogger(StringHelper.class);

    private static int TRAN = 0;

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str)) {
            return true;
        } else if (str.length() <= 0) {
            return true;
        } else if (str.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断字符串是否不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 中文乱码
     *
     * @param str     字符串
     * @param encoded 编码格式，UTF-8或GBK
     * @return
     */
    public static String chineseStrEncoded(String str, String encoded) {
        if (isEmpty(str)) {
            str = "";
        } else {
            try {
                str = (new String(str.getBytes("ISO-8859-1"), encoded)).trim();
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("中文乱码处理异常");
                logger.error("中文乱码处理异常" + e);
            }
        }
        return str;
    }

    /**
     * String转Date
     *
     * @param str     String日期
     * @param pattern 转换日期格式
     * @return 例如：str="2017-01-01"
     * type="yyyy-MM-dd"
     */
    public static Date strToDate(String str, String pattern) {
        if (isEmpty(str)) {
            return null;
        } else {
            try {
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                return format.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
                logger.info("日期转换处理异常");
                logger.error("日期转换处理异常" + e);
                return null;
            }
        }
    }

    /**
     * 返回当前日期
     *
     * @param pattern 日期格式
     * @return
     */
    public static String nowDate(String pattern) {
        return dateToString(new Date(), pattern);
    }

    /**
     * Date日期转String
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String dateToString(Date date, String pattern) {
        if (date == null) {
            return "";
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        }
    }

    /**
     * 返回当前年
     *
     * @return
     */
    public static String getYear() {
        Calendar calendar = Calendar.getInstance();
        return String.valueOf(calendar.get(1));
    }

    /**
     * 返回当前月
     *
     * @return
     */
    public static String getMonth() {
        Calendar calendar = Calendar.getInstance();
        String temp = String.valueOf(calendar.get(2) + 1);
        if (temp.length() < 2){
            temp = "0" + temp;
        }
        return temp;
    }

    /**
     * 返回当前天
     *
     * @return
     */
    public static String getDay() {
        Calendar cal = Calendar.getInstance();
        String temp = cal.get(Calendar.DATE) + "";
        if (temp.length() < 2){
            temp = "0" + temp;
        }
        return temp;
    }

    /**
     * 去除String空格
     *
     * @param param
     * @return
     */
    public static String nvl(String param) {
        return param != null ? param.trim() : "";
    }

    /**
     * 编码转换GBK转UTF-8
     *
     * @param s
     * @return
     */
    public static String setGBToUTF8(String s) {
        try {
            StringBuffer out = new StringBuffer("");
            byte[] bytes = s.getBytes("unicode");
            for (int i = 2; i < bytes.length - 1; i += 2) {
                out.append("\\u");
                String str = Integer.toHexString(bytes[i + 1] & 0xff);
                for (int j = str.length(); j < 2; j++) {
                    out.append("0");
                }
                out.append(str);
                String str1 = Integer.toHexString(bytes[i] & 0xff);
                for (int j = str1.length(); j < 2; j++) {
                    out.append("0");
                }

                out.append(str1);
            }
            return out.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成编号
     *
     * @param str (编号开头字母)
     * @return
     */
    public static synchronized String getStrNumber(String str) {
        TRAN++;
        return str + System.currentTimeMillis() + TRAN;
    }


    /**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        String regEx = "^[-\\+]?[\\d]*$";
        Pattern pattern = Pattern.compile(regEx);
        return pattern.matcher(str).matches();
    }

    /**
     * 判断传入的整型是否为null或者为空字符串
     * @param i
     * @return
     */
    public static boolean isNotNumber(Integer i) {

        if(i == null){
            return false;
        }
        if(i.toString().trim() == ""){
            return false;
        }
        return true;
    }

    /***
     * 时间戳转换成日期格式字符串
     * @param seconds               精确到秒的字符串
     * @param format
     * @return
     */
    public static String timeStampToDate(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || "null".equals(seconds)){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }

    /***
     * 日期格式字符串转换成时间戳
     * @param dateStr                  字符串日期
     * @param format                    yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String dateToTimeStamp(String dateStr,String format){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(dateStr).getTime()/1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * 取得当前时间戳（精确到秒）
     * @return
     */
    public static String timeStamp(){
        long time = System.currentTimeMillis();
        String t = String.valueOf(time/1000);
        return t;
    }

    /**
     * 转义特殊字符
     * @param str
     * @return
     */
    public static String specialChar(String str) {
        if (str.contains("%")) {
            str = str.replace("%", "\\%");
        }
        if (str.contains("'")) {
            str = str.replace("'", "\\'");
        }
        if (str.contains("-")) {
            str = str.replace("'", "\\-");
        }
        return str;
    }

    /***
     * 判断两个时间之间的间隔，单位秒
     * @param start         起始时间
     * @param end           结束时间
     * @return
     */
    public static long checkTwoTime(Date start,Date end) {
        long interval = 0;
        try {
            interval = (end.getTime() - start.getTime())/1000;
        }catch (Exception e){
            e.printStackTrace();
        }
        return interval;
    }

    /***
     * 手机号码校验
     * * @param phone
     * @return
     */
    public static boolean isMobile(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        boolean flag = false;
        if (phone.length() != 11) {
            return flag;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    /**
     * d电话号码校验
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        Pattern p1 = null, p2 = null;
        Matcher m = null;
        boolean b = false;
        // 验证带区号的
        String p1Str = "^[0][1-9]{2,3}-[0-9]{5,10}$";
        p1 = Pattern.compile(p1Str);
        // 验证没有区号的
        String p2Str = "^[1-9]{1}[0-9]{5,8}$";
        p2 = Pattern.compile(p2Str);
        if (phone.length() > 9) {
            m = p1.matcher(phone);
            b = m.matches();
        } else {
            m = p2.matcher(phone);
            b = m.matches();
        }
        return b;
    }

    /**
     * 获取过去任意天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> PastDates(int intervals ) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = 0; i <intervals; i++) {
            pastDaysList.add(getPastDate(i+1));
        }
        return pastDaysList;
    }

    /**
     * 获取未来任意天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> FetureDates(int intervals ) {
        ArrayList<String> fetureDaysList = new ArrayList<>();
        for (int i = 0; i <intervals; i++) {
            fetureDaysList.add(getFetureDate(i+1));
        }
        return fetureDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取未来 第 past 天的日期
     * @param past
     * @return
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取过去任意月内的月份数组
     * @param intervals      intervals月内
     * @return              月份数组
     */
    public static ArrayList<String> PastMonths(int intervals ) {
        ArrayList<String> pastMonthsList = new ArrayList<>();
        for (int i = 0; i <intervals; i++) {
            pastMonthsList.add(getPastMonth(i+1));
        }
        return pastMonthsList;
    }

    /**
     * 获取过去第个月的月份
     * @param past
     * @return
     */
    public static String getPastMonth(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取过去几年内的月份数组
     * @param intervals      intervals月内
     * @return              月份数组
     */
    public static ArrayList<String> PastYears(int intervals ) {
        ArrayList<String> pastMonthsList = new ArrayList<>();
        for (int i = 0; i < intervals; i++) {
            String year = getPastYear(i+1);
            for(int j = 1; j <= 12; j++){
                String month = j<10?"0"+j:""+j;
                pastMonthsList.add(year+"-"+month);
            }
        }
        return pastMonthsList;
    }

    /**
     * 获取过去第个年的年份
     * @param past
     * @return
     */
    public static String getPastYear(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        String result = format.format(today);
        return result;
    }

    public static void main(String[] args) {
        ArrayList<String> pastDaysList = PastYears(1);
        ArrayList<String> months = StringHelper.PastMonths(6);
        System.out.println("pastDaysList:"+pastDaysList);
        System.out.println("months:"+months);
    }
}
